package com.ktwlsoft.archivemanage.domain.business.repositoryService.sms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ktwlsoft.archivemanage.domain.dao.entity.Account;
import com.ktwlsoft.archivemanage.domain.dao.entity.sms.*;
import com.ktwlsoft.archivemanage.domain.dao.repository.sms.SmsLogMapper;
import com.ktwlsoft.archivemanage.domain.dao.repository.sms.SmsTemplateMapper;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import com.ktwlsoft.archivemanage.service.security.UserPrincipal;
import com.ktwlsoft.archivemanage.service.utils.SmsHelperUtils;
import com.ktwlsoft.archivemanage.service.utils.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * 短信服务接口实现
 *
 * @author zhuhe on 2019-10-24 14:19:41
 * @version 1.0
 */
@Service
public class SmsService {

    @Autowired
    private SmsLogMapper smsLogMapper;

    @Autowired
    private SmsTemplateMapper smsTemplateMapper;

    @Autowired
    private SmsConfig smsConfig;

    /**
      * 短信发送 on 2021/1/5 10:02
      *
      * @param channel 短信渠道
      * @param templateEncoded 短信模板编码
      * @param phone 待发送手机号
      * @param map 短信模板变量
      * @return Result<?>
      */
    public Result<?> sendSms(String channel,String templateEncoded,String phone,Map<String,String> map){
        //发送短信
        SendSms sendSms = new SendSms();
        //短信渠道
        sendSms.setSmsChannel(channel == null || "".equals(channel)?"1":channel);
        //短信模板编码
        sendSms.setSmsTemplateEncoded(templateEncoded);
        //待发送手机号
        String[] strings = new String[]{phone};
        sendSms.setPhoneNumbers(strings);
        //短信模板变量
        sendSms.setParamMap(map);
        return sendSms(sendSms);
    }

    /**
     * 短信发送
     *
     * @param model model
     * @return ResponseEntity<Object>
     */
    public Result<?> sendSms(SendSms model) {
        if (model.getSmsTemplateEncoded() == null || "".equals(model.getSmsTemplateEncoded().trim())) {
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("短信模板编码不能为空");
        }
        if (model.getPhoneNumbers().length <= 0) {
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("待发送手机号不能为空");
        }
        String templateParam = "";
        if (model.getParamMap() != null && model.getParamMap().size() > 0) {
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(model.getParamMap()));
            templateParam = jsonObject.toString();
        }
        //短信模板信息
        SmsTemplate template = smsTemplateMapper.getFindByCode(model.getSmsTemplateEncoded());
        if(template == null){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("该模板数据不存在");
        }
        Account account = UserPrincipal.getCurrentUser();
        //短信日志
        SmsLog smsLog = new SmsLog();
        smsLog.setId(SnowFlake.getNextId());
        smsLog.setMobile(joinArrayWithSeparator(model.getPhoneNumbers(), ","));
        smsLog.setDisplayContent(replaceContenParam(template.getTemplateText(), model.getParamMap()));
        smsLog.setContent(templateParam);
        smsLog.setAccountId(account != null?String.valueOf(account.getId()):null);
        smsLog.setCreateTime(new Date());
        switch (model.getSmsChannel()) {
            case "1":
                SmsParam smsRequest = new SmsParam();
                smsRequest.setAccessKeyId(smsConfig.getAccessKeyId());
                smsRequest.setAccessKeySecret(smsConfig.getAccessKeySecret());
                smsRequest.setSignName(template.getTemplateSign());
                smsRequest.setTemplateCode(template.getTemplateCode());
                smsRequest.setPhoneNumbers(joinArrayWithSeparator(model.getPhoneNumbers(), ","));
                smsRequest.setTemplateParam(templateParam);
                boolean result = SmsHelperUtils.sendSms(smsRequest);
                if (!result) {
                    smsLog.setStatus(0);
                    smsLog.setRemark(smsRequest.getErrorMsg());
                    smsLog.setContent(JSONObject.toJSONString(smsRequest));
                    smsLogMapper.insert(smsLog);
                    return Result.body(model, ResultType.CHECK_ERROR).withMessage("短信发送失败：" + smsRequest.getErrorMsg());
                }
                break;
            default:
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("该短信渠道未集成");
        }
        smsLog.setStatus(1);
        smsLogMapper.insert(smsLog);
        return Result.ok("success");
    }

    /**
     * 替换内容参数
     *
     * @param content 待替换内容
     * @param paramMap 传入参数
     * @return String
     */
    private String replaceContenParam(String content, Map<String, String> paramMap) {
        String resultStr = content;
        if (paramMap != null && paramMap.size() > 0) {
            for (Map.Entry<String, String> item : paramMap.entrySet()) {
                resultStr = resultStr.replace("${" + item.getKey() + "}", item.getValue());
            }
        }
        return resultStr;
    }

    private static String joinArrayWithSeparator(String[] strings, String separator) {
        StringBuilder sb = new StringBuilder();
        for (String s : strings) {
            sb.append(s);
            sb.append(separator);
        }
        if (sb.length() > 1) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }
}
